import store from '@/store'
import router from '@/router'

const fetchAndAddRoutes = async function () {
    console.log('fetch routes old routes', router.getRoutes())
    const res = await store.dispatch('user/getUserInfo');
    await store.dispatch('menus/setMenus', res.menus)
    console.log('menus', store.state.menus.menus)

    const routes = filterAsyncRoutes(res.menus)
    routes.forEach(route => {
        router.addRoute(route)
    })
    // 路由最后加入404
    router.addRoute({
        path: '*',
        name: 'Page404',
        component: () => import('@/views/error/Page404.vue')
    })
    console.log('add dynamic route new routes', router.getRoutes())
}

// 路由过滤 遍历路由 转换为组件对象和路径
function filterAsyncRoutes(data) {
    if (data && data.length) {
        return data.filter(item => !item.isExternal).map(item => {
            const route = {
                path: item.path,
                name: item.name,
            }
            if (!item.component) {
                route.component = () => import('@/layout')
            } else {
                route.component = loadView(item.component)
            }
            if (item.children) {
                route.children = filterAsyncRoutes(item.children)
            }
            return route
        })
    } else {
        return []
    }
}

// 路由拼接
function loadView(view) {
    return () => import(`@/views/${view}`)
}

export default {
    fetchAndAddRoutes
}
